package cloud.health.framework.computing.core;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 全局配置读取
 */
@Slf4j
public class GlobalProperties {

    private static final String APPLICATION_YAML = "application.yml";
    private static final ConcurrentHashMap<String, Object> PROPERTIES = new ConcurrentHashMap<>();

    /**
     * 读取配置
     */
    @SneakyThrows
    public static void read() {
        try {
            InputStream in = Yaml.class.getClassLoader().getResourceAsStream(APPLICATION_YAML);
            Yaml yaml = new Yaml();
            PROPERTIES.putAll(yaml.loadAs(in, Map.class));
        } catch (Exception e) {
            log.error("READ PROPERTIES ERROR -->", e);
        }
    }

    /**
     * 所有配置
     */
    public static Map<String, Object> all() {
        return PROPERTIES;
    }

    /**
     * 获取指定配置对象
     */
    public static <T> T get(String key, Class klass) {
        Object obj = PROPERTIES.get(key);
        if (Objects.isNull(obj)) {
            throw new NullPointerException("指定配置信息不存在");
        }
        return (T) JSON.parseObject(JSON.toJSONString(obj), klass);
    }

    /**
     * 获取配置对象列表
     */
    public static <T> List<T> array(String key, Class klass) {
        Object obj = PROPERTIES.get(key);
        if (Objects.isNull(obj)) {
            throw new NullPointerException("指定配置信息不存在");
        }
        return JSON.parseArray(JSON.toJSONString(obj), klass);
    }
}
